package com.rainman.mybatisplus.core;

import com.rainman.mybatisplus.joinparam.JoinParam;

public class JoinStrUtil {


    /**
     * 处理连表后面的  a left join tablename b on a.xxx=b.xxx
     *
     * @param sb
     * @param joinParam
     */
    public static void dealJoinInfo(StringBuilder sb, JoinParam joinParam){

        int tableNameStart= sb.indexOf(" FROM ")+6;
        int tableNameEnd=0;


        boolean start=false;
        for(int i=tableNameStart;i<sb.length();i++){
            char c = sb.charAt(i);
            if(!start){//未定位到tableName
                if(!Character.isSpaceChar(c)){
                    start=true;
                }
            }else {//已定位到tableName

                if(Character.isSpaceChar(c)){
                    tableNameEnd=i+1;
                    break;
                }

            }

        }

        sb.insert(tableNameEnd,
                new StringBuilder().append(" ").append(joinParam.getAsName()).append(joinParam.getFinalJoinStr())
                        .append(" ")
        );



    }

    /**
     * 处理需要被查询的出来的字段
     *
     * @param sb
     * @param joinParam
     */
    public static  void dealSelect(StringBuilder sb,JoinParam joinParam){


        int selectIndex=sb.indexOf("SELECT ");
        int fromIndex=sb.indexOf(" FROM ");

        String selectSt=sb.substring(selectIndex+7,fromIndex);//获取原有的select

        sb.replace(selectIndex+7,fromIndex,"");//去除原有的select
        // System.out.println(selectSt);

        Boolean exAll=joinParam.getExSelect().contains(",*,");


        String[] split = selectSt.split(",");

        String needDouHead=" ";

        for(int i=0;i<split.length;i++){
            String s=split[i];

            if(s.trim().length()<=0){
                continue;
            }

            if(!s.contains(".")){//需处理 原先没有带.的 判断为基准表的字段

                if(!exAll){//如果把基准表所有的字段去除 则不操作
                    if(!joinParam.getExSelect().contains(s.trim())){//不在去除之列

                        sb.insert(sb.indexOf(" FROM "),needDouHead+joinParam.getAsName()+"."+s.trim());
                        needDouHead=",";
                    }

                }


            }else {//无需处理  原先有带.的

                sb.insert(sb.indexOf(" FROM "),needDouHead+s.trim());
                needDouHead=",";

            }

        }

        //---------------------处理jp中的select字段-----------------
        String selectStr = joinParam.getSelectStr();

        if(selectStr!=null&&selectStr.trim().length()>1){

            String[] selectStrSpit = selectStr.trim().split(",");

            for(String selectS:selectStrSpit){

                if(selectS.trim().length()<=0){
                    continue;
                }

                sb.insert(sb.indexOf(" FROM "),needDouHead+selectS.trim());
                needDouHead=",";

            }

        }
        //---------------------------------------------------------



    }


}
